package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.annotation.FrontCache;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping
    @Transactional
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("接收到前端传来的数据:{}", dishDto);

        dishService.savewithflaver(dishDto);
        redisTemplate.delete("dish_" + dishDto.getCategoryId() + "_1");
        return R.success("成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {

        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByAsc(Dish::getSort);
        Page<Dish> dishPage = dishService.page(pageInfo, lqw);
        Page<DishDto> dishDtoPage = dishService.pageWithCategory(dishPage);

        return R.success(dishDtoPage);
    }

    //    通过id获取产品
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = new DishDto();
        Dish dish = dishService.getById(id);
        BeanUtils.copyProperties(dish, dishDto);
        DishDto dishDto1 = dishService.get(dishDto);
        return R.success(dishDto1);
    }

    //    修改产品
    @PutMapping
    @Transactional
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateById(dishDto);
        Long dishId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dishId);
        dishFlavorService.remove(lqw);
        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        for (DishFlavor dishFlavor : dishFlavors) {
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(dishFlavors);

        Set<Object> keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    //    查询页面
    @GetMapping("/list")
    @FrontCache("dish_+")
    public R<List<DishDto>> list(Dish dish) {
        String key = "dish_" + dish.getCategoryId() + "_" + 1;
        List<DishDto> inRedisList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (inRedisList != null) {
            return R.success(inRedisList);
        }

//        查询数据库操作
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.like(StringUtils.isNotEmpty(dish.getName()), Dish::getName, dish.getName());
        lqw.eq(Dish::getStatus, 1);
        List<Dish> dishList = dishService.list(lqw);

        List<DishDto> dishDtoList = new ArrayList<>();

        dishList.forEach(item -> {
            LambdaQueryWrapper<DishFlavor> dishFlaverLqw = new LambdaQueryWrapper<>();
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishFlaverLqw.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlaverLqw);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        });

//        存入redis中
        redisTemplate.opsForValue().set(key,dishDtoList,24, TimeUnit.HOURS);

        return R.success(dishDtoList);
    }

    //    批量起售和停售
    @PostMapping("/status/{id}")
    public R<String> setstatus(@PathVariable Integer id, @RequestParam("ids") ArrayList<Long> ids) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId, ids);
        List<Dish> list = dishService.list(lqw);

        list.forEach(dish -> dish.setStatus(id));

        dishService.updateBatchById(list);

        Set<Object> keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);

        return R.success("操作成功");
    }

    @DeleteMapping
    @Transactional
//    删除产品
    public R<String> delete(@RequestParam("ids") ArrayList<Long> ids) {

//        通过Long类型的集合接收
        dishService.removeByIds(ids);
        ArrayList<Long> dishFlavorsList = new ArrayList<>();
        for (Long id : ids) {
            dishFlavorsList.add(id);
        }
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(lqw);

//        删除缓冲
        Set<Object> keys = redisTemplate.keys("dish*");
        redisTemplate.delete(keys);
//        用Long数组接收的批量删除
        for (Long id : ids) {
            dishService.removeById(id);
            LambdaQueryWrapper<DishFlavor> relqw = new LambdaQueryWrapper<>();
            relqw.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(relqw);
        }

        return R.success("删除成功");
    }

}
